﻿using CefSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApp1
{
    public class WinFormResourceRequestHandler : ResourceRequestHandler
    {
        public static bool EnableSaveData = false;
        public static string SaveDataDir = "";
        protected override IResponseFilter GetResourceResponseFilter(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response)
        {
            var filter = FilterManager.CreateFilter(request.Identifier.ToString());
            return filter;
        }

        protected override void OnResourceLoadComplete(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
        {
            //if (request.Url.ToLower().Contains("login".ToLower()))
            if (EnableSaveData)
            {
                try
                {
                    var filter = FilterManager.GetFileter(request.Identifier.ToString()) as TestJsonFilter;
                    //ASCIIEncoding encoding = new ASCIIEncoding();
                    //这里截获返回的数据
                    //var data = encoding.GetString(filter.DataAll.ToArray());
                    int idx = request.Url.IndexOf("/", 8);
                    string filedir = "index_default.html";
                    if (idx > 0) filedir = request.Url.Substring(idx).Split('?')[0].Replace("/", "\\");
                    if (filedir == "\\") filedir = "index_default.html";
                    string filename = Path.Combine(SaveDataDir, filedir.Trim('\\'));
                    string dir = Path.GetDirectoryName(filename);
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    File.WriteAllBytes(filename, filter.DataAll.ToArray());
                }
                catch
                {

                }
            }

        }
    }
}
